package at.gv.bmwf.fons.model.ontology.static_impl;

import at.gv.bmwf.fons.model.ontology.JenaResource;
import at.gv.bmwf.fons.model.ontology.uris.VONT;

import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;

public class StaticResource implements JenaResource {
	private static int uidNumber = 0;
	private static Boolean first = true;

	private final Resource resource;
	private Integer uid;

	protected StaticResource (Resource resource) {
		this.resource = resource;
		synchronized (first) {
			if (first) {
				ResultSet result = 
						execSelect(String.format("SELECT (MAX(?uid) as ?maxUid) WHERE { ?s <%s> ?uid. }", VONT.uid));
				if (result.hasNext()) {
					QuerySolution solution = result.next();
					uidNumber = solution.contains("?maxUid") ? solution.getLiteral("?maxUid").getInt() : 0;
				}
				first = false;
			}
		}
	}

	@Override
	public Resource getResource() {
		return this.resource;
	}

	@Override
	public Model getModel() {
		return this.resource.getModel();
	}

	protected ResultSet execSelect (String queryString) {
		return QueryExecutionFactory.create(QueryFactory.create(queryString, VONT.prefix), getModel()).execSelect();
	}

	@Override
	public int hashCode() {
		if (uid == null) {
			Statement stmt = resource.getProperty(VONT.uid); 
			if (stmt == null) {
				resource.addLiteral(VONT.uid, uid = uidNumber++);
			} else {
				uid = stmt.getLiteral().getInt();
			}
		}
		return uid;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		StaticResource other = (StaticResource) obj;
		return this.hashCode() == other.hashCode();
	}
}
